package com.ctl.config;

import com.ctl.server.NettyServer;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.concurrent.Future;

@Slf4j
@EnableScheduling
@Component
public class ServerConfig {
    @Autowired
    private NettyServer nettyServer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MapBeanConfig mapBeanConfig;
    @Value("${netty.address}")
    public String hostname;
    @Value("${netty.port:8090}")
    public Integer port;
    @Autowired
    @Qualifier("serviceExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @PostConstruct
    public void init() {
        threadPoolTaskExecutor.submit(() -> nettyServer.start(new InetSocketAddress(hostname, port)));
    }


    // @Scheduled(fixedDelay = 5000)
    public void task() {
        Iterator<String> iterator = mapBeanConfig.getCtx().keySet().iterator();
        while (iterator.hasNext()) {
            try {
                String id = iterator.next();
                Object obj = mapBeanConfig.getCtx().get(id);
                if (obj.getClass().getSimpleName().contains("ChannelHandlerContext")) {
                    ChannelHandlerContext chc = (ChannelHandlerContext) obj;
                    chc.write(id + "#" + System.currentTimeMillis());
                    chc.flush();
                }
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
}
